package com.ming.common.beetl.util;

import com.ming.common.beetl.entity.BaseEntity;

import java.lang.reflect.Field;
import java.util.Map;

public class BeanUtil {

    /*public static <T> T convert(Map<String, Object> map, Class<T> clazz) throws Exception {
        T obj = clazz.newInstance();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value);
        }
        return obj;
    }*/

    public static <T extends BaseEntity> T convert(Map<String, Object> map, Class<T> clazz) throws Exception {
        T obj = clazz.newInstance();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, convert(value,field.getType().getName()));
        }
        return obj;
    }

    public static <T> T convert(Object obj, String targetType) {
        switch (targetType){
            case "java.lang.String": return (T) convert(obj, String.class);
            case "java.lang.Long": return (T) convert(obj, Long.class);
            case "java.lang.Integer": return (T) convert(obj, Integer.class);
            case "java.lang.Double": return (T) convert(obj, Double.class);
            case "java.lang.Boolean": return (T) convert(obj, Boolean.class);
            default: return null;
        }
    }

    public static <T> T convert(Object obj, Class<T> targetType) {
        if (obj == null) {
            return null;
        }
        if (targetType.isInstance(obj)) {
            return targetType.cast(obj);
        }
        // 根据目标类型进行相应的转换操作
        if (targetType == String.class) {
            return (T) obj.toString();
        } else if (targetType == Integer.class || targetType == int.class) {
            return (T) Integer.valueOf(obj.toString());
        } else if (targetType == Double.class || targetType == double.class) {
            return (T) Double.valueOf(obj.toString());
        } else if (targetType == Boolean.class || targetType == boolean.class) {
            return (T) Boolean.valueOf(obj.toString());
        }
        // 可以根据需要添加其他类型的转换逻辑
        return null;
    }
}
